package com.zut.chat.service;

import com.zut.chat.dto.WebSocketMessage;
import com.zut.chat.entity.ChatBotConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 聊天机器人自动回复服务
 */
@Slf4j
@Service
public class ChatBotAutoReplyService {

    @Autowired
    private ChatBotConfigService chatBotConfigService;

    @Autowired
    private ChatWebSocketService chatWebSocketService;

    @Autowired
    private ChatMessageService chatMessageService;
    
    @Autowired
    private VideoService videoService;

    private final Random random = new Random();
    
    // 记录每个机器人的最后回复时间
    private final Map<Long, Long> botLastReplyTime = new ConcurrentHashMap<>();

    /**
     * 处理消息并判断是否需要机器人自动回复
     */
    @Async
    public void processMessage(String messageContent, String senderNickname) {
        try {
            // 获取启用自动回复的机器人配置
            List<ChatBotConfig> autoReplyBots = chatBotConfigService.getAutoReplyEnabledBots();
            
            for (ChatBotConfig bot : autoReplyBots) {
                if (shouldReply(bot, messageContent, senderNickname)) {
                    scheduleReply(bot, messageContent);
                }
            }
        } catch (Exception e) {
            log.error("处理机器人自动回复时发生错误", e);
        }
    }

    /**
     * 判断是否应该回复
     */
    private boolean shouldReply(ChatBotConfig bot, String messageContent, String senderNickname) {
        // 机器人不回复自己的消息
        if (bot.getBotName().equals(senderNickname)) {
            return false;
        }

        // 检查回复间隔
        Long lastReplyTime = botLastReplyTime.get(bot.getId());
        long currentTime = System.currentTimeMillis();
        
        if (lastReplyTime != null) {
            long timeSinceLastReply = currentTime - lastReplyTime;
            if (timeSinceLastReply < bot.getMinReplyInterval()) {
                return false; // 还在最小回复间隔内
            }
        }

        // 只有包含触发关键词时才回复
        return bot.shouldTriggerReply(messageContent);
    }

    /**
     * 安排回复（延迟发送）
     */
    private void scheduleReply(ChatBotConfig bot, String originalMessage) {
        try {
            // 计算回复延迟时间
            long minDelay = bot.getMinReplyInterval();
            long maxDelay = bot.getMaxReplyInterval();
            long delay = minDelay + random.nextInt((int) Math.max(1, maxDelay - minDelay));

            // 延迟执行回复
            Thread.sleep(delay);

            // 选择回复消息
            List<String> replyMessages = bot.getReplyMessageList();
            if (replyMessages.isEmpty()) {
                return;
            }

            String replyContent = replyMessages.get(random.nextInt(replyMessages.size()));

            // 发送回复消息
            sendBotReply(bot, replyContent);

            // 更新最后回复时间
            botLastReplyTime.put(bot.getId(), System.currentTimeMillis());

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.warn("机器人回复被中断: {}", bot.getBotName());
        } catch (Exception e) {
            log.error("机器人 {} 发送回复时发生错误", bot.getBotName(), e);
        }
    }

    /**
     * 发送机器人回复消息
     */
    private void sendBotReply(ChatBotConfig bot, String content) {
        try {
            LocalDateTime now = LocalDateTime.now();

            // 创建机器人消息
            WebSocketMessage botMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.AI_ROBOT)
                    .senderNickname(bot.getBotName())
                    .content(content)
                    .timestamp(now)
                    .onlineCount(chatWebSocketService.getOnlineCount())
                    .build();

            // 广播消息到所有客户端
            chatWebSocketService.broadcastMessage(botMessage);

            // 保存消息到数据库
            chatMessageService.saveMessage(botMessage);

            log.info("机器人 {} 发送回复: {}", bot.getBotName(), content);

        } catch (Exception e) {
            log.error("发送机器人回复消息时发生错误", e);
        }
    }

    /**
     * 手动触发机器人回复（用于测试）
     */
    public void triggerManualReply(String botName, String content) {
        try {
            ChatBotConfig bot = chatBotConfigService.findByBotName(botName);
            if (bot != null && bot.getEnabled()) {
                sendBotReply(bot, content);
            }
        } catch (Exception e) {
            log.error("手动触发机器人回复时发生错误", e);
        }
    }

    /**
     * 重置机器人回复时间（用于管理）
     */
    public void resetBotReplyTime(Long botId) {
        botLastReplyTime.remove(botId);
    }

    /**
     * 获取机器人最后回复时间
     */
    public Long getBotLastReplyTime(Long botId) {
        return botLastReplyTime.get(botId);
    }
    
    /**
     * 处理视频请求
     */
    @Async
    public void handleVideoRequest(String requesterNickname) {
        try {
            // 获取启用的机器人配置
            List<ChatBotConfig> enabledBots = chatBotConfigService.getEnabledBots();
            
            if (enabledBots.isEmpty()) {
                log.warn("没有可用的机器人处理视频请求");
                return;
            }
            
            // 随机选择一个机器人来发送视频
            ChatBotConfig selectedBot = enabledBots.get(random.nextInt(enabledBots.size()));
            
            // 获取随机视频URL
            videoService.getRandomVideoUrl()
                    .subscribe(
                        videoUrl -> {
                            if (videoUrl != null && !videoUrl.trim().isEmpty()) {
                                sendBotVideoMessage(selectedBot, videoUrl, requesterNickname);
                            } else {
                                // 视频获取失败，发送文字消息
                                String fallbackMessage = "抱歉，暂时无法获取视频，请稍后再试～";
                                sendBotReply(selectedBot, fallbackMessage);
                            }
                        },
                        error -> {
                            log.error("获取视频URL失败", error);
                            String errorMessage = "视频获取失败了呢，要不试试其他的？";
                            sendBotReply(selectedBot, errorMessage);
                        }
                    );
                    
        } catch (Exception e) {
            log.error("处理视频请求时发生错误", e);
        }
    }
    
    /**
     * 发送机器人视频消息
     */
    private void sendBotVideoMessage(ChatBotConfig bot, String videoUrl, String requesterNickname) {
        try {
            LocalDateTime now = LocalDateTime.now();
            
            // 生成视频消息的文字描述
            String[] videoDescriptions = {
                "给你找了个有趣的小视频～",
                "来看看这个视频吧！",
                "分享一个精彩视频给大家～",
                "这个视频应该不错哦！",
                "送你一个小视频，希望你喜欢！"
            };
            String description = videoDescriptions[random.nextInt(videoDescriptions.length)];
            
            // 如果有指定请求者，添加@提及
            if (requesterNickname != null && !requesterNickname.trim().isEmpty()) {
                description = "@" + requesterNickname + " " + description;
            }

            // 创建视频消息
            WebSocketMessage videoMessage = WebSocketMessage.builder()
                    .type(WebSocketMessage.MessageType.VIDEO)
                    .senderNickname(bot.getBotName())
                    .content(description)
                    .videoUrl(videoUrl)
                    .videoTitle("随机小视频")
                    .timestamp(now)
                    .onlineCount(chatWebSocketService.getOnlineCount())
                    .build();

            // 广播消息到所有客户端
            chatWebSocketService.broadcastMessage(videoMessage);

            // 保存消息到数据库
            chatMessageService.saveMessage(videoMessage);

            log.info("机器人 {} 发送视频消息: {}", bot.getBotName(), videoUrl);

        } catch (Exception e) {
            log.error("发送机器人视频消息时发生错误", e);
        }
    }
} 